#include "StdAfx.h"
#include "Language.h"

#include "FileReader.h"
#include "Settings.h"

CLanguage::CLangMap CLanguage::s_langMap;

bool CLanguage::Initialize()
{
  CString file = CSettings::GetAppFolder();
  file += SETTINGS.GetString(sLanguagePath);
  file += TEXT("\\");
  file += SETTINGS.GetString(sLanguage);
  file += LANGUAGE_FILE_EXT;
  return LoadStrings(file.GetString());
}

void CLanguage::Terminate()
{
}

const TCHAR* CLanguage::Get(const TCHAR* key)
{
  if (!key)
    return TEXT("");

  CString sKey = key;
  sKey.MakeLower();
  CLangMap::iterator iter = s_langMap.find(sKey);
  if (iter != s_langMap.end())
    return iter->second.GetString();
  else
    return key;
}

const TCHAR* CLanguage::GetFmt(const TCHAR* key, ...)
{
  static TCHAR buf[4096];
  va_list args;
  va_start(args, key);
  vswprintf(buf, Get(key), args);
  va_end(args);
  return buf;
}

bool CLanguage::LoadStrings(const TCHAR* szFile)
{
  if (!szFile)
    return false;

  CString key, val;
  CFileReader file(szFile);
  while (file.ReadPair(key, val))
  {
    key.MakeLower();
    s_langMap.insert(std::pair<CString, CString>(key, val));
  }

  return s_langMap.size() > 0;
}
